#include "utils/socket.h"
#include <iostream>

using namespace cox;

// 组播接收端
void testMulticastReceiver() {
	// 创建UDP socket
	Socket recvSocket(Socket::UDP);
	if (recvSocket.getFd() < 0) {
		std::cerr << "创建接收Socket失败" << std::endl;
		return;
	}

	// 绑定组播地址和端口（必须绑定组播端口才能接收）
	NetAddr multicastAddr("224.2.2.4", 9000); // 组播地址范围：224.0.0.0-239.255.255.255
	if (!recvSocket.bind(multicastAddr)) {
		std::cerr << "绑定组播地址失败，错误码：" << recvSocket.getError() << std::endl;
		return;
	}

	// 加入组播组（本地网卡IP，若为0.0.0.0则自动选择）
	if (!recvSocket.addMemberShip("224.2.2.4", "0.0.0.0")) {
		std::cerr << "加入组播组失败" << std::endl;
		return;
	}
	std::cout << "组播服务已启动：" << multicastAddr.host << ":" << multicastAddr.port << std::endl;

	// 循环接收组播消息
	while (true) {
		char      buf[1024] = {0};
		NetAddr   senderAddr;
		long long recvLen = recvSocket.recvfrom(buf, 1023, senderAddr);
		if (recvLen > 0) {
			std::cout << "收到组播消息（来自" << senderAddr.host << ":" << senderAddr.port << "）：" << buf << std::endl;
		}
	}
}

// 组播发送端
void testMulticastSender() {
	// 创建UDP socket
	Socket sendSocket(Socket::UDP);
	if (sendSocket.getFd() < 0) {
		std::cerr << "创建发送Socket失败" << std::endl;
		return;
	}

	// 向组播地址发送消息
	NetAddr     multicastAddr("224.2.2.4", 9000);
	const char *msg     = "这是一条组播消息！";
	long long   sendLen = sendSocket.sendto(msg, strlen(msg), multicastAddr);
	if (sendLen < 0) {
		std::cerr << "组播发送失败，错误码：" << sendSocket.getError() << std::endl;
	} else {
		std::cout << "组播消息发送成功，长度：" << sendLen << std::endl;
	}
}

// 编译：g++ -std=c++11 -o multicast_test multicast_test.cpp -lpthread
int main() {
	testMulticastReceiver();

	// testMulticastSender();
	return 0;
}
